import request, { service, sseConfig } from '@/utils/request'

// 声明基本路径
let basePath = window.location.pathname.includes('test') ? '/test-wrag-ai/' : '/wrag-ai/'

/**
 * 聊天相关的 API 请求
 */

/**
 * 创建新的会话
 * @param {Object} data - 会话数据
 * @returns {Promise<Object>} 返回会话信息
 */
export function createNewConversation(data) {
    return request({
        url: basePath + 'conversation/new',
        method: 'post',
        data
    })
}

/**
 * 发送聊天消息
 * @param {Object} data - 消息数据
 * @param {string} data.conversationCode - 会话编码
 * @param {string} data.messageCode - 消息编码
 * @param {string} data.question - 问题内容
 * @returns {Promise<Object>} 返回响应数据
 */
export function sendMessage(data) {
    return request({
        url: basePath + 'chat/send',
        method: 'post',
        data: {
            conversationCode: data.conversationCode,
            messageCode: data.messageCode,
            question: data.question
        }
    })
}

/**
 * 获取历史会话列表
 * @param {Object} params - 查询参数
 * @returns {Promise<Object>} 返回历史会话列表
 */
export function getHistoryList(params) {
    return request({
        url: basePath + 'conversation/list',
        method: 'get',
        params
    })
}

/**
 * 获取会话详情
 * @param {string} id - 会话ID
 * @returns {Promise<Object>} 返回会话详情
 */
export function getConversationDetail(id) {
    return request({
        url: `${basePath}conversation/detail/${id}`,
        method: 'get'
    })
}

/**
 * 建立 SSE 连接
 * @returns {Promise<Object>} 返回 SSE 连接
 */
export async function connectSSE() {
    console.log('Connecting to SSE endpoint...');
    try {
        // 使用 service 实例进行请求
        const response = await service({
            url: basePath + 'chat/connect',
            method: 'GET',
            headers: {
                'Accept': 'text/event-stream',
                'Cache-Control': 'no-cache'
            },
            ...sseConfig
        });

        console.log('SSE connection response:', {
            status: response.status,
            statusText: response.statusText,
            headers: response.headers,
            ok: response.ok
        });

        // 检查响应状态
        if (!response.ok) {
            throw new Error(`SSE connection failed with status ${response.status}`);
        }

        // 检查响应头
        const contentType = response.headers['content-type'];
        console.log('Response content type:', contentType);
        
        if (contentType && !contentType.includes('text/event-stream')) {
            console.warn('Unexpected content type:', contentType);
        }

        // 获取响应数据
        const data = response.data;
        console.log('SSE connection data:', data);

        // 确保返回完整的 URL
        let url = data?.url;
        if (!url) {
            console.warn('No URL in response, using default endpoint');
            url = basePath + 'chat/connect';
        }
        
        console.log('Final SSE URL:', url);
        
        return {
            url,
            status: response.status,
            headers: response.headers
        };
    } catch (error) {
        console.error('SSE connection error:', {
            message: error.message,
            cause: error.cause,
            stack: error.stack
        });
        throw error;
    }
}

/**

 * @param {number} data.satisfaction - 满意度评分 (1: 满意, -1: 不满意)
 * @returns {Promise<Object>} 返回响应数据
 */
export function evaluate(data) {
    return request({
        url: basePath + 'conversation/evaluate',
        method: 'post',
        data
    })
}


export function getCurrentLoginUserInfo(data) {
    return request({
        url: basePath + 'login/getCurrentLoginUserInfo',
        method: 'get',
        data
    })
}
export function userConversation(data) {
    return request({
        url: basePath + 'conversation/userConversation',
        method: 'post',
        data
    })
}

export function userConversationDetails(data) {
    return request({
        url: `${basePath}conversation/${data.conversationId}/details`,
        method: 'get',
        data
    })
}
export function checkLogin(data) {
    return request({
        url: `${basePath}user/checkLogin`,
        method: 'get',
        data
    })
}
export function newMessage(params) {
    return request({
        url: `${basePath}conversation/newMessage`,
        method: 'get',
        params
    })
}

export function createSignature(params) {
    return request({
        url: `${basePath}speech/createSignature`,
        method: 'get',
        params
    })
}

export function conversationDelete(data) {
    return request({
        url: `${basePath}conversation/delete`,
        method: 'post',
        data
    })
}